package virtualpostit.com;

import java.lang.reflect.Type;
import java.util.ArrayList;
import model.PostIt;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

/**
 * Attività che permette all'utente di visualizzare la lista dei post-it associati
 * ad un punto d'interesse. In particolare saranno visualizzati come item della lista
 * il nome sintetico del post-it, la valutazione corrente riferita all'affidabilità 
 * dell'autore e in più uno sarà visualizzata un'icona rappresentante la categoria del post-it.
 * 
 * @author Gruppo Capo, De Notaris, Pastore e Vento
 * @since Luglio 2011
 */
public class PostItListViewActivity extends ListActivity {

	private class RatingAdapter extends ArrayAdapter<RowModel> {


		public RatingAdapter(ArrayList<RowModel> list) {
			super(PostItListViewActivity.this, R.layout.list_item, R.id.tvItem, list);
		}

		public View getView(int position, View convertView,	ViewGroup parent) {
			View row=super.getView(position, convertView, parent);
			ViewHolder holder=(ViewHolder)row.getTag();
			if (holder==null) {
				holder=new ViewHolder(row);
				row.setTag(holder);
			}

			RowModel model=getModel(position);
			holder.rate.setRating(model.getRating());
			holder.tvItem.setText(" "+model.getItem());
			holder.icon.setImageResource(model.getIcon());
			return row;

		}
	}

	private class ViewHolder {

		TextView tvItem=null;
		RatingBar rate=null;
		ImageView icon=null;

		ViewHolder(View base) {
			this.tvItem=(TextView)base.findViewById(R.id.tvItem);
			this.rate=(RatingBar)base.findViewById(R.id.rbAff);
			this.icon=(ImageView)base.findViewById(R.id.ivIcon);
		}
	}

	class RowModel {
		private String item;
		private float rating;
		private int icon;

		RowModel(String item,float rating,int icon) {
			this.item=item;
			this.rating=rating;
			this.icon=icon;
		}
		public String getItem(){
			return item;
		}
		public float getRating(){
			return rating;
		}
		public int getIcon(){
			return icon;
		}

	}

	// Attributi di classe
	private ArrayList<RowModel> nameList;
	private ArrayList<PostIt> list ;

	@Override
	public void onCreate(final Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_view);
		nameList = new ArrayList<RowModel>();
		postIt();
		TextView distance= (TextView) findViewById(R.id.distance);
		distance.append(getIntent().getExtras().getString(getPackageName()+".distance").concat(" km"));
		setListAdapter(new RatingAdapter(nameList));
		ListView lv = getListView();
		lv.setTextFilterEnabled(true);
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {   	
				nextActivity(position);
			}

		});
	}

	// Metodo che carica i post-it associati ad un punto d'interesse
	private void postIt(){
		MyDialog md = new MyDialog(this);
		String response="";

		WebService namePostIt = new WebService(LoginActivity.SERVER_HOST + ":"	+ LoginActivity.SERVER_PORT);
		ArrayList<NameValuePair> params = new ArrayList<org.apache.http.NameValuePair>();
		String cat = getIntent().getExtras().getString(getPackageName()+".cathegory");
		String id = String.valueOf(getIntent().getExtras().getInt(getPackageName()+".id"));
		params.add(new BasicNameValuePair("cathegory", cat ));
		params.add(new BasicNameValuePair("waypoint", id));
		Log.i("Parametro categoria post-it:", cat);
		Log.i("Parametro id del post-it:", id);
		response = namePostIt.webPost("/infoPostIt.php", params);

		try {

			String r = response.replace("\n", "");
			Log.i("response", r);

			if (!r.equals("null")) {
				Type collectionType = new TypeToken<ArrayList<PostIt>>() {}.getType();
				list = new Gson().fromJson(response,collectionType);
				for (PostIt p : list) {
					Log.i("categoria post-it", p.getCathegory());
					if (p.getCathegory().equals("Ristorazione"))
						nameList.add(new RowModel(p.getName(),p.getRanking(),R.drawable.cutlery));
					else if (p.getCathegory().equals("Alloggi"))
						nameList.add(new RowModel(p.getName(),p.getRanking(),R.drawable.hotel));
					else if (p.getCathegory().equals("Strutture Commerciali"))
						nameList.add(new RowModel(p.getName(),p.getRanking(),R.drawable.store));
					else if (p.getCathegory().equals("Rifornimento Carburante"))
						nameList.add(new RowModel(p.getName(),p.getRanking(),R.drawable.fuel));
				}

			} 

		} catch (Exception e) {
			Log.d("Errore", e.getMessage());
			md.showDialog("Attenzione",	"Errore del server, riprovare più tardi", R.drawable.error);
		}
	}

	// Metodo che passa il controllo alla prossima attività al verificarsi di un evento
	private void nextActivity(int position) {
		Intent myIntent = new Intent(this.getBaseContext(),	PostItInfoActivity.class);
		myIntent.putExtra("postit", list.get(position));
		startActivity(myIntent);		
	}

	private RowModel getModel(int position) {
		return ((RatingAdapter)getListAdapter()).getItem(position);
	}

}